package cn.controller;

import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.common.ConfigOption;
import cn.common.ExceResult;
import cn.common.ExcelHandler;
import cn.common.GridCommon;
import cn.common.LayTable;
import cn.filter.LoginCheck;
import cn.kpi.entity.attendance.AttSummaryEntity;
import cn.kpi.entity.sys.OrgEntity;
import cn.kpi.entity.usualassessment.UserUATMzpdSummaryEntity;
import cn.kpi.service.pingyou.IPyResultService;
import cn.kpi.service.sys.IOrgService;

@Controller
@RequestMapping("pyresult")
public class PyResultController extends BaseController {
    @Autowired
    private IPyResultService iPyResultService;

    @Autowired
    private IOrgService iOrgService;

    @RequestMapping(value = "/pyresult_list")
    public String PyResultList(Model model) {
        try {
            //List<OrgEntity> orglst = iOrgService.GetOrgList();
            String where = " AND orgid IN (" + this.GetOrgListByRole() + ")";
            List<OrgEntity> orglst = iOrgService.GetOrgListByWhere(where);
            for (int i = 0; i < orglst.size(); i++) {
                String html = "";
                for (int j = 0; j < orglst.get(i).getLevel(); j++) {
                    html += "&#12288;";
                }
                orglst.get(i).setOrgname(html + orglst.get(i).getOrgname());
            }
            model.addAttribute("orglst", orglst);
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            year = year -1;
            model.addAttribute("year", year);
        } catch (Exception ex) {

        }
        return "pingyou/pyresult_list";
    }

    @RequestMapping(value = "/pyresult_tj_list")
    public String PyResultTjList(Model model) {
        try {
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH) + 1;
            int quarter = 1;
            switch (month) {
                case 1:
                case 2:
                case 3:
                    quarter = 1;
                    break;
                case 4:
                case 5:
                case 6:
                    quarter = 2;
                    break;
                case 7:
                case 8:
                case 9:
                    quarter = 3;
                    break;
                case 10:
                case 11:
                case 12:
                    quarter = 4;
                    break;
            }
            if (quarter == 1) {
                year=year-1;
                quarter=4;
            } else {
                quarter = quarter - 1;
            }

            model.addAttribute("year", year);
            model.addAttribute("quarter", quarter);
        } catch (Exception ex) {

        }
        return "pingyou/pyresult_tj_list";
    }

    @RequestMapping(value = "/pyresult_tj_edit")
    public String PyResultTjEdit(Model model, Long orgstatustjid, Long orgid, int year, int quarter, int status) {
        try {
            OrgEntity entity = iOrgService.GetOrgById(orgid);
            model.addAttribute("orgstatustjid", orgstatustjid);
            model.addAttribute("orgid", orgid);
            model.addAttribute("year", year);
            model.addAttribute("quarter", quarter);
            model.addAttribute("status", status);
            model.addAttribute("entity", entity);
        } catch (Exception ex) {

        }
        return "pingyou/pyresult_tj_edit";
    }


    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_summary_list")
    public LayTable<UserUATMzpdSummaryEntity> GetSummaryList(HttpServletRequest request) {

        List<UserUATMzpdSummaryEntity> lst = null;
        LayTable<UserUATMzpdSummaryEntity> layTable = new LayTable<UserUATMzpdSummaryEntity>();
        try {
            int year = Integer.parseInt(request.getParameter("year"));
            String zzpdjg = request.getParameter("zzpdjg");
            String dymzpyjg = request.getParameter("dymzpyjg");
            String szdw = request.getParameter("szdw");
            String username = request.getParameter("username");
            if (username.trim().equals("")) {
                username = "";
            } else {
                username=" and  realname like '%"+username+"%'";
            }
            String where = "";

            if (zzpdjg != null && zzpdjg.length() > 0) {
                where += " AND (B.yzzpdjg='" + zzpdjg + "' OR B.ezzpdjg='" + zzpdjg + "' OR B.szzpdjg='" + zzpdjg + "' OR B.sizzpdjg='" + zzpdjg + "') ";
            }
            if (dymzpyjg != null && dymzpyjg.length() > 0) {
                where += " AND (B.ydymzpyjg='" + dymzpyjg + "' OR B.edymzpyjg='" + dymzpyjg + "' OR B.sdymzpyjg='" + dymzpyjg + "' OR B.sidymzpyjg='" + dymzpyjg + "') ";
            }
            if (szdw != null && szdw.length() > 0 && !szdw.equals("0")) {
                OrgEntity orgentity = iOrgService.GetOrgById(Long.parseLong(szdw));
                where += " AND szdw IN (SELECT orgid FROM t_sys_org WHERE lft>=" + orgentity.getLft() + " AND lft<=" + orgentity.getRgt() + ")";
            } else {
                where += this.GetUserListByRole();
            }

            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            int beginrow = (page - 1) * limit;
            int endrow = limit;

            String wherelimit = where + " ORDER BY C.orderindex LIMIT " + beginrow + "," + endrow;

            lst = iPyResultService.GetMzpdSummaryListByWhere(wherelimit, year, username);
            for (int i = 0; i < lst.size(); i++) {
                int numr = (page - 1) * limit + (i + 1);
                lst.get(i).setRowNum(numr);
            }

            int iCount = iPyResultService.GetMzpdSummaryListCountByWhere(where, year, username);
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);

        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }

    @ResponseBody
    @RequestMapping(value = "/update_mzpdsummarystatus")
    public ExceResult UpdateMzpdSummaryStatus(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            Long mzpdsummaryid = Long.parseLong(request.getParameter("mzpdsummaryid"));
            int iResult = iPyResultService.UpdateMzpdSummaryStatusById(mzpdsummaryid, 2);
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }


    @ResponseBody
    @RequestMapping(value = "/get_list_org_tj")
    public GridCommon<Map> GetListOrgTj(HttpServletRequest request) {
        GridCommon<Map> countlist = new GridCommon<Map>();
        try {
            int year = Integer.parseInt(request.getParameter("year"));
            int quarter = Integer.parseInt(request.getParameter("quarter"));
            String orgid = request.getParameter("orgid");
            String strorgids = this.GetOrgListByRole();

            String where = "";
            where += " AND orgid IN(" + strorgids + ") ";

            if (orgid != null && orgid.length() > 0) {
                OrgEntity orgentity = iOrgService.GetOrgById(Long.parseLong(orgid));
                where += " AND orgid IN (SELECT orgid FROM t_sys_org WHERE lft>=" + orgentity.getLft() + " AND lft<=" + orgentity.getRgt() + ")";
            }

            //季度考核汇总，当前组织机构在岗人数
            List<Map> list = new ArrayList<>();

            //取值是否有归档
            list = iPyResultService.GetOldOrgPyResultTjList(where, year, quarter);

            if (list == null || list.size() == 0) {
                //11.1考核汇总，只看在职
                where += " AND userstatus='在职'";
                list = iPyResultService.GetOrgPyResultTjList(where, year, quarter);
            }
            System.out.println(list);
            int zgrsCount = 0;
            int xjcountCount = 0;
            int haocountCount = 0;
            int hgcountCount = 0;
            int chacountCount = 0;
            int bdjgcountCount = 0;
            int bcjkhrsCount = 0;
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map = list.get(i);
                if (map.get("zgrs") != null) {
                    zgrsCount += Integer.parseInt(map.get("zgrs").toString());
                }
                if (map.get("xjcount") != null) {
                    xjcountCount += Integer.parseInt(map.get("xjcount").toString());
                }
                if (map.get("cjkhrsxj") != null) {
                    map.put("xjcount", map.get("cjkhrsxj"));
                    xjcountCount += Integer.parseInt(map.get("cjkhrsxj").toString());
                }
                if (map.get("haocount") != null) {
                    haocountCount += Integer.parseInt(map.get("haocount").toString());
                }
                if (map.get("cjkhrsh") != null) {
                    map.put("haocount", map.get("cjkhrsh"));
                    haocountCount += Integer.parseInt(map.get("cjkhrsh").toString());
                }
                if (map.get("hgcount") != null) {
                    hgcountCount += Integer.parseInt(map.get("hgcount").toString());
                }
                if (map.get("cjkhrshg") != null) {
                    map.put("hgcount", map.get("cjkhrshg"));
                    hgcountCount += Integer.parseInt(map.get("cjkhrshg").toString());
                }
                if (map.get("chacount") != null) {
                    chacountCount += Integer.parseInt(map.get("chacount").toString());
                }
                if (map.get("cjkhrsc") != null) {
                    map.put("chacount", map.get("cjkhrsc"));
                    chacountCount += Integer.parseInt(map.get("cjkhrsc").toString());
                }
                if (map.get("bdjgcount") != null) {
                    bdjgcountCount += Integer.parseInt(map.get("bdjgcount").toString());
                }
                if (map.get("cjkhrsbdkhjg") != null) {
                    map.put("bdjgcount", map.get("cjkhrsbdkhjg"));
                    bdjgcountCount += Integer.parseInt(map.get("cjkhrsbdkhjg").toString());
                }
                if (map.get("bcjkhrs") != null) {
                    bcjkhrsCount += Integer.parseInt(map.get("bcjkhrs").toString());
                }
                if (map.get("wcjkhrs") != null) {
                    map.put("bcjkhrs", map.get("wcjkhrs"));
                    bcjkhrsCount += Integer.parseInt(map.get("wcjkhrs").toString());
                }
            }

            Map<String, Object> map1 = new HashMap<String, Object>();
            //orgname=巡察考核办, year=2018, zgrs=22, orgparentid=46, orgid=109, quarter=2
            map1.put("orgname", "合计");
            map1.put("year", year);
            map1.put("zgrs", zgrsCount);
            map1.put("orgparentid", 0);
            map1.put("orgid", 1);
            map1.put("quarter", quarter);

            map1.put("xjcount", xjcountCount);
            map1.put("haocount", haocountCount);
            map1.put("hgcount", hgcountCount);
            map1.put("chacount", chacountCount);
            map1.put("bdjgcount", bdjgcountCount);
            map1.put("bcjkhrs", bcjkhrsCount);

            list.add(0, map1);
            System.out.println(list);
            countlist.setCurrentPage(1);
            countlist.setPageSize(10);
            countlist.setItems(list);
            countlist.setStatus(0);
            countlist.setMsg("");
        } catch (Exception e) {
            countlist.setCurrentPage(1);
            countlist.setPageSize(10);
            countlist.setItems(null);
            countlist.setStatus(1);
            countlist.setMsg("操作成功");
            e.printStackTrace();
        }
        return countlist;
    }


    @RequestMapping(value = "/update_org_status")
    public String AddLoanUserJs(HttpServletRequest request, HttpServletResponse response) {
        try {
            String strorgstatustjid = request.getParameter("orgstatustjid");
            String strorgid = request.getParameter("orgid");
            String stryear = request.getParameter("year");
            String strquarter = request.getParameter("quarter");
            String strstatus = request.getParameter("status");


            String remark = request.getParameter("remark");

            int status = Integer.parseInt(strstatus);
            Long orgstatustjid = Long.parseLong(strorgstatustjid);
            Long orgid = Long.parseLong(strorgid);
            int year = Integer.parseInt(stryear);
            int quarter = Integer.parseInt(strquarter);


            int iResult = 0;
            if (status == 2) {
                iResult = iPyResultService.UpdateOrgStatusGd(this.GetLoginUserId(), orgstatustjid, remark);
//				iResult += iPyResultService.backDataByStatusGd(year,quarter);//固化季度数据,改到提报时固化数据
            } else if (status == 3) {
                iResult = iPyResultService.UpdateOrgStatusBh(this.GetLoginUserId(), orgstatustjid, remark, orgid, year, quarter);
            }

            return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
        } catch (Exception ex) {
            return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
        }
    }


    @ResponseBody
    @RequestMapping(value = "/export_excel_all")
    public ExceResult ExportExcelAll(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            int year = Integer.parseInt(request.getParameter("year"));
            String zzpdjg = request.getParameter("zzpdjg");
            String dymzpyjg = request.getParameter("dymzpyjg");
            String szdw = request.getParameter("szdw");
            String username = request.getParameter("username");
            if (username.trim().equals("")) {
                username = "";
            } else {
                username=" and  realname like '%"+username+"%'";
            }
            String where = "";

            if (zzpdjg != null && zzpdjg.length() > 0) {
                where += " AND (B.yzzpdjg='" + zzpdjg + "' OR B.ezzpdjg='" + zzpdjg + "' OR B.szzpdjg='" + zzpdjg + "' OR B.sizzpdjg='" + zzpdjg + "') ";
            }
            if (dymzpyjg != null && dymzpyjg.length() > 0) {
                where += " AND (B.ydymzpyjg='" + dymzpyjg + "' OR B.edymzpyjg='" + dymzpyjg + "' OR B.sdymzpyjg='" + dymzpyjg + "' OR B.sidymzpyjg='" + dymzpyjg + "') ";
            }


            if (szdw != null && szdw.length() > 0 && !szdw.equals("0")) {
                OrgEntity orgentity = iOrgService.GetOrgById(Long.parseLong(szdw));
                where += " AND szdw IN (SELECT orgid FROM t_sys_org WHERE lft>=" + orgentity.getLft() + " AND lft<=" + orgentity.getRgt() + ")";
            } else {
                where += this.GetUserListByRole();
            }


            String wherelimit = where + " ORDER BY C.orderindex ";

            List<UserUATMzpdSummaryEntity> lst = iPyResultService.GetMzpdSummaryListByWhere(wherelimit, year, username);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

            //String finalXlsxPath=ConfigOption.getInstance().getTemplateurl()+"/kqtemp.xlsx";
            //String filename=ConfigOption.getInstance().getTemplateurl()+"/考勤_"+sdf.format(new Date())+".xlsx";

            String finalXlsxPath = ConfigOption.getInstance().getTemplateurl() + "/ndpyjgtemp.xlsx";
            String filename = "ndpyjg_" + sdf.format(new Date()) + ".xlsx";
            Boolean olResult = ExcelHandler.writeExcelNdpyjg(lst, finalXlsxPath, filename, response, year);

            if (olResult) {
                result.setCode(200);
                result.setResult(1);
                String urlen = ConfigOption.getInstance().getWeburl() + filename;
                result.setMsg(urlen);
            } else {
                result.setCode(300);
                result.setResult(0);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }


}
